package com.alibaba.citrus.ots.unified.inventory.repository.impl;

import com.alibaba.citrus.ots.unified.inventory.repository.AllocateOrderReadRepository;
import com.alibaba.citrus.ots.unified.inventory.repository.EsAllocateApplyOrderIndexRepository;
import com.alibaba.citrus.ots.unified.inventory.utils.AllocateApplyOrdeUtils;
import com.alibaba.citrus.ots.unified.inventory.utils.EnumUtils;
import com.alibaba.citrus.ots.unified.inventory.utils.InfoUtil;
import com.alibaba.citrus.ots.unified.inventory.utils.OtsDateUtils;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.model.dto.BaselineGetOrganizationByIdsRequest;
import com.epoch.app.bcots.model.dto.BatchQueryWarehouseByIdsRequest;
import com.epoch.app.bcots.service.BaseDataService;
import com.epoch.app.bcots.service.UnifiedInventoryService;
import com.epoch.app.otsplatformenhance.api.organizationquery.service.OrganizationQueryService;
import com.epoch.app.otsplatformenhance.domain.customeraddress.service.CustomerAddressService;
import com.epoch.app.otsplatformenhance.dto.request.IdQueryRequest;
import com.epoch.app.otsplatformenhance.model.dto.BatchQueryCustomersRequest;
import com.epoch.app.otsplatformenhance.sdo.OrganizationSDO;
import com.epoch.app.otsplatformenhance.service.OtsPlatformEnhanceService;
import com.epoch.app.otsunifiedinventory.api.allocateorderread.service.AllocateOrderReadService;
import com.epoch.app.otsunifiedinventory.domain.esallocateapplyorderindex.model.EsAllocateApplyOrderIndex;
import com.epoch.app.otsunifiedinventory.domain.esallocateapplyorderindex.service.EsAllocateApplyOrderIndexService;
import com.epoch.app.otsunifiedinventory.dto.request.AllocateOrderDetailSearchRequest;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateApplyOrderListDTO;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateOrderDetailVO;
import com.epoch.app.otsunifiedinventory.dto.response.AllocateOrderGetCustomerResponse;
import com.epoch.app.otsunifiedinventory.model.dto.AllocateApplyOrderQueryRequest;
import com.epoch.app.otsunifiedinventory.model.dto.CustomerAndAddressInfo;
import com.epoch.app.otsunifiedinventory.model.dto.QueryEsAllocateApplyOrderIndexListRequest;
import com.epoch.app.otsunifiedinventory.sdo.enums.AllocateApplyOrderStatusEnum;
import com.epoch.app.otsunifiedinventory.sdo.enums.ReasonForRejectionEnum;
import com.epoch.app.otsunifiedinventory.sdo.enums.TransportModeEnum;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Set;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;

/**
 * @author wanwy
 * @description
 */
@Component
public class EsAllocateApplyOrderIndexRepositoryImpl implements EsAllocateApplyOrderIndexRepository {

    Log logger = Log.getLogger(EsAllocateApplyOrderIndexRepositoryImpl.class);
    /**
     * 销售组织
     */
    private static final Integer SALES_ORGANIZATION = 104;
    private static final long dayTime = 86399900L;
    @Resource
    private EsAllocateApplyOrderIndexService allocateApplyOrderIndexService;

    @Autowired
    private BaseDataService baseDataService;

    @Autowired
    private OtsPlatformEnhanceService otsPlatformEnhanceService;

    @Autowired
    private UnifiedInventoryService unifiedInventoryService;

    @Autowired
    private AllocateOrderReadRepository allocateOrderReadRepository;

    @Resource
    @Qualifier("allocateOrderReadServiceImpl")
    private AllocateOrderReadService allocateOrderReadService;

    @Resource
    private CustomerAddressService customerAddressService;

    @Resource
    private OrganizationQueryService organizationQueryService;


//    @Resource(name = "allocateApplyOrderTaskExecutor")
//    private ThreadPoolTaskExecutor allocateApplyOrderTaskExecutor;

    private Map<String, String> getOrganizationMap(Set<String> applyOrgIds){
        Map<String, String> organizationMap = new HashMap<>();
        BaselineGetOrganizationByIdsRequest baselineGetOrganizationByIdsRequest = new BaselineGetOrganizationByIdsRequest();
        baselineGetOrganizationByIdsRequest.setIds(new ArrayList(applyOrgIds));
        Map baselineGetOrganizationByIdsMap = (Map) baseDataService.baselineGetOrganizationByIds(baselineGetOrganizationByIdsRequest);
        if (Objects.nonNull(baselineGetOrganizationByIdsMap)) {
            List<Map> organization = (List<Map>) baselineGetOrganizationByIdsMap.get("result");
            if (Objects.nonNull(organization)) {
                for (Map map : organization) {
                    if (Objects.nonNull(map.get("organizationSDO"))) {
                        Map organizationSDO = (Map) map.get("organizationSDO");
                        if (Objects.nonNull(organizationSDO.get("id")) && Objects.nonNull(organizationSDO.get("name"))) {
                            organizationMap.put(organizationSDO.get("id").toString(), organizationSDO.get("name").toString());
                        }
                    }

                }
            }
        }
        return organizationMap;
    }

    @Override
    public Result<List<AllocateApplyOrderListDTO>> queryEsAllocateApplyOrderIndexList(AllocateApplyOrderQueryRequest allocateApplyOrderQueryRequest) {

        //查询es数据
        QueryEsAllocateApplyOrderIndexListRequest queryEsAllocateApplyOrderIndexListRequest = getEsAllocateApplyOrderRequest(allocateApplyOrderQueryRequest);

        logger.info("queryEsAllocateApplyOrderIndexList方法入参:{}", JSON.toJSONString(queryEsAllocateApplyOrderIndexListRequest));
        Result<List<EsAllocateApplyOrderIndex>> listResult = allocateApplyOrderIndexService.queryEsAllocateApplyOrderIndexList(queryEsAllocateApplyOrderIndexListRequest);
        Result<Long> total = allocateApplyOrderIndexService.getEsAllocateApplyOrderIndexListTotal(queryEsAllocateApplyOrderIndexListRequest);
        logger.info("queryEsAllocateApplyOrderIndexList方法返回值:{}", JSON.toJSONString(listResult));
        List<AllocateApplyOrderListDTO> allocateApplyOrderListDTOS = new ArrayList<>();
        Result result = new Result();
        if (Objects.nonNull(listResult) && Objects.nonNull(listResult.getResult())) {
            List<EsAllocateApplyOrderIndex> esAllocateApplyOrderIndices = listResult.getResult();
            //组织id集合
            Set<String> applyOrgIds = new HashSet<>();
            //地址id集合
            Set<String> addressIds = new HashSet<>();
            //仓库id集合
            Set<String> warehouseIds = new HashSet<>();
            //仓库档案id集合
            Set<String> cargoZoneIds = new HashSet<>();

            for (EsAllocateApplyOrderIndex allocateApplyOrderIndex : esAllocateApplyOrderIndices) {
                //获取组织id
                Long mainApplyOrgId = allocateApplyOrderIndex.getMainApplyOrgId();
                if (Objects.nonNull(mainApplyOrgId)) {
                    applyOrgIds.add(mainApplyOrgId.toString());
                }
                //获取销售组织id
                String saleOrganizationCode = allocateApplyOrderIndex.getMainSaleOrganizationCode();
                if (Objects.nonNull(saleOrganizationCode)) {
                    applyOrgIds.add(saleOrganizationCode);
                }
                //获取地址id
                String addressId = allocateApplyOrderIndex.getMainCustomerAddressId();
                if (Objects.nonNull(addressId)) {
                    addressIds.add(addressId);
                }
                //获取收货仓id
                Long receiveWarehouseId = allocateApplyOrderIndex.getMainReceiveWarehouseId();
                if (Objects.nonNull(receiveWarehouseId)) {
                    warehouseIds.add(receiveWarehouseId.toString());
                }
                //获取发货仓id
                Long shipWarehouseId = allocateApplyOrderIndex.getMainShipWarehouseId();
                if (Objects.nonNull(shipWarehouseId)) {
                    warehouseIds.add(shipWarehouseId.toString());
                }

                //获取收货仓档案id
                Long receiveCargoZoneId = allocateApplyOrderIndex.getMainReceiveCargoZoneId();
                if (Objects.nonNull(receiveCargoZoneId)) {
                    cargoZoneIds.add(receiveCargoZoneId.toString());
                }

                //获取fa货仓档案id
                Long shipCargoZoneId = allocateApplyOrderIndex.getMainShipCargoZoneId();
                if (Objects.nonNull(shipCargoZoneId)) {
                    cargoZoneIds.add(shipCargoZoneId.toString());
                }
            }

            Map<String, CompletableFuture<Map<String, String>>> futureMap = new HashMap<>();
            //提报组织
            Map<String, String> organizationMap = new HashMap<>();
            try {
                if (Objects.nonNull(applyOrgIds)) {
                    organizationMap = getOrganizationMap(applyOrgIds);
                }
            } catch (Throwable e) {
                logger.error("AllocateApplyOrderReadServiceImpl.enrichInfo.getOrganizationInfo error", e);
            }

            //获取地址编码查找 客户信息
            Map<String,CustomerAndAddressInfo> customer = new HashMap();
            try {
                //地址信息
                if(CollectionUtils.isNotEmpty(addressIds)){
                    List<CustomerAndAddressInfo> customerAndAddressInfos = AllocateApplyOrdeUtils.getCustomerAndAddressInfo(new ArrayList<>(addressIds));
                    for (CustomerAndAddressInfo customerAndAddressInfo:customerAndAddressInfos){
                        customer.put(customerAndAddressInfo.getCustomerAddressId(),customerAndAddressInfo);
                    }
                }

//                if (CollectionUtils.isNotEmpty(addressIds)) {
//                    BatchQueryAddressRequest request = new BatchQueryAddressRequest();
//                    request.setAddressCodes(new ArrayList(addressIds));
//                    Object data = otsPlatformEnhanceService.batchQueryAddress(request);
//                    if (Objects.nonNull(data)) {
//                        JSONObject js = JSON.parseObject(JSON.toJSONString(data));
//                        if (Objects.nonNull(js)) {
//                            JSONArray array = js.getJSONArray("result");
//                            if (array != null && array.size() > 0) {
//                                for (int i = 0; i < array.size(); i++) {
//                                    JSONObject object = array.getJSONObject(i);
//                                    if (object == null) {
//                                        continue;
//                                    }
//                                    customer.put(object.getString("addressCode"), object);
//                                }
//                            }
//                        }
//                    }
//                }
            } catch (Throwable e) {
                logger.error("AllocateApplyOrderReadServiceImpl.enrichInfo.getCustomerAddressInfo error", e);
            }

            //获取仓库信息
            Map<String, JSONObject> warehouseIdMap = new HashMap<>();
            try {
                if (Objects.nonNull(warehouseIds)) {
                    BatchQueryWarehouseByIdsRequest batchQueryWarehouseByIdsRequest = new BatchQueryWarehouseByIdsRequest();
                    batchQueryWarehouseByIdsRequest.setWarehouseIds(new ArrayList(warehouseIds));
                    batchQueryWarehouseByIdsRequest.setModelList(Lists.newArrayList(1, 3, 5));
                    Object data = unifiedInventoryService.batchQueryWarehouseByIds(batchQueryWarehouseByIdsRequest);
                    if (Objects.nonNull(data)) {
                        JSONObject js = JSON.parseObject(JSON.toJSONString(data));
                        if (Objects.nonNull(js)) {
                            JSONArray array = js.getJSONArray("result");
                            if (Objects.nonNull(array) && array.size() > 0) {
                                for (int i = 0; i < array.size(); i++) {
                                    JSONObject object = array.getJSONObject(i);
                                    if (Objects.nonNull(object)) {
                                        warehouseIdMap.put(object.getString("id"), object);
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Throwable e) {
                logger.error("AllocateApplyOrderReadServiceImpl.enrichInfo.getWarehouseAreaInfo error", e);
            }

            //获取仓库档案信息
            Map<String, JSONObject> cargoZoneIdMap = new HashMap<>();
            try {
                if (Objects.nonNull(cargoZoneIds)) {
                    BatchQueryWarehouseByIdsRequest batchQueryWarehouseByIdsRequest = new BatchQueryWarehouseByIdsRequest();
                    batchQueryWarehouseByIdsRequest.setWarehouseIds(new ArrayList(cargoZoneIds));
                    batchQueryWarehouseByIdsRequest.setModelList(Lists.newArrayList(1, 3));
                    Object data = unifiedInventoryService.batchQueryWarehouseByIds(batchQueryWarehouseByIdsRequest);
                    if (Objects.nonNull(data)) {
                        JSONObject js = JSON.parseObject(JSON.toJSONString(data));
                        if (Objects.nonNull(js)) {
                            JSONArray array = js.getJSONArray("result");
                            if (Objects.nonNull(array) && array.size() > 0) {
                                for (int i = 0; i < array.size(); i++) {
                                    JSONObject object = array.getJSONObject(i);
                                    if (Objects.nonNull(object)) {
                                        cargoZoneIdMap.put(object.getString("id"), object);
                                    }
                                }
                            }
                        }
                    }
                }
            } catch (Throwable e) {
                logger.error("AllocateApplyOrderReadServiceImpl.enrichInfo.getWarehouseInfo error", e);
            }

            /**
             * 获取发货量
             * 1.拿到预报单id，根据预报单id 查到调拨单数据
             * 2、遍历出调拨单id和map（调拨单id，预报单id） 查询调拨单明细
             *4、字段赋值时循环调拨单明细累加值
             */
            Map<String, List<AllocateOrderDetailVO>> allocateApplyOrderAndAllocateOrderDetailRelationshipMap = new HashMap<>();
            try {
                Set<String> codes = esAllocateApplyOrderIndices.stream().map(EsAllocateApplyOrderIndex::getMainCode).collect(Collectors.toSet());
                //预报单与调拨单明细关系map
                AllocateOrderDetailSearchRequest allocateOrderDetailSearchRequest = new AllocateOrderDetailSearchRequest();
                allocateOrderDetailSearchRequest.setAllocateApplyOrderCodeList(new ArrayList<>(codes));
                //查询到 调拨单的物流信息
                Result<List<AllocateOrderDetailVO>> allocateOrderDetailVOSResult = allocateOrderReadService.searchForAllocateApplyOrder(allocateOrderDetailSearchRequest);
                if (Objects.nonNull(allocateOrderDetailVOSResult) && CollectionUtils.isNotEmpty(allocateOrderDetailVOSResult.getResult())) {
                    for (AllocateOrderDetailVO allocateOrderDetailVO : allocateOrderDetailVOSResult.getResult()) {
                        String allocateApplyOrderAndAllocateOrderDetailRelationshipMapKey = allocateOrderDetailVO.getAllocateApplyOrderCode() + allocateOrderDetailVO.getScItemCode();
                        List<AllocateOrderDetailVO> allocateOrderDetails = allocateApplyOrderAndAllocateOrderDetailRelationshipMap.get(allocateApplyOrderAndAllocateOrderDetailRelationshipMapKey);
                        if (Objects.nonNull(allocateOrderDetails)) {
                            allocateOrderDetails.add(allocateOrderDetailVO);
                            allocateApplyOrderAndAllocateOrderDetailRelationshipMap.put(allocateApplyOrderAndAllocateOrderDetailRelationshipMapKey, allocateOrderDetails);
                        } else {
                            allocateApplyOrderAndAllocateOrderDetailRelationshipMap.put(allocateApplyOrderAndAllocateOrderDetailRelationshipMapKey, Lists.newArrayList(allocateOrderDetailVO));
                        }
                    }
                }
            } catch (Throwable e) {
                logger.error("AllocateApplyOrderReadServiceImpl.enrichInfo.getShipAndLogisticsInfo error", e);
            }

            //es数据转换dto
            for (EsAllocateApplyOrderIndex esAllocateApplyOrderIndex : esAllocateApplyOrderIndices){
                allocateApplyOrderListDTOS.add(esAllocateApplyOrderIndexsTransformationAllocateApplyOrderListDTO(esAllocateApplyOrderIndex
                        ,allocateApplyOrderAndAllocateOrderDetailRelationshipMap,customer,warehouseIdMap,cargoZoneIdMap,organizationMap));
            }
            //批量填充预报单的分公司客户，避免for循环，提升性能
            enrichBranchCustomerInfo(esAllocateApplyOrderIndices, allocateApplyOrderListDTOS);

            //添加页码数
            if (Objects.nonNull(total)) {
                result.setTotal(total.getResult().intValue());
            } else {
                result.setTotal(listResult.getTotal());
            }
            result.setResult(allocateApplyOrderListDTOS);
            result.setSuccess(true);
            return result;
        }
        result.setTotal(0);
        result.setResult(allocateApplyOrderListDTOS);
        result.setSuccess(true);
        return result;
    }

    //获取es查询入参
    private QueryEsAllocateApplyOrderIndexListRequest getEsAllocateApplyOrderRequest(AllocateApplyOrderQueryRequest allocateApplyOrderQueryRequest) {
        QueryEsAllocateApplyOrderIndexListRequest queryEsAllocateApplyOrderIndexListRequest = new QueryEsAllocateApplyOrderIndexListRequest();
        queryEsAllocateApplyOrderIndexListRequest.setSize(allocateApplyOrderQueryRequest.getSize());
        queryEsAllocateApplyOrderIndexListRequest.setPage(allocateApplyOrderQueryRequest.getPage());
        queryEsAllocateApplyOrderIndexListRequest.setStart((allocateApplyOrderQueryRequest.getSize() * allocateApplyOrderQueryRequest.getPage()) - allocateApplyOrderQueryRequest.getSize());
        queryEsAllocateApplyOrderIndexListRequest.setLimit(allocateApplyOrderQueryRequest.getSize());
        queryEsAllocateApplyOrderIndexListRequest.setOutAllocateApplyOrderIds(allocateApplyOrderQueryRequest.getOutAllocateApplyOrderIds());
//        预报单号
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getCode())) {
            queryEsAllocateApplyOrderIndexListRequest.setCode(allocateApplyOrderQueryRequest.getCode());
        }
//        外部预调拨单号
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getOutAllocateApplyOrderId())) {
            queryEsAllocateApplyOrderIndexListRequest.setOutAllocateApplyOrderId(allocateApplyOrderQueryRequest.getOutAllocateApplyOrderId());
        }
//        调拨单号
//        if (Objects.nonNull(allocateApplyOrderQueryRequest.())){
//            queryEsAllocateApplyOrderIndexListRequest.setAllocateOrderNo(allocateApplyOrderQueryRequest.().toString());
//        }
//        借货调拨单号
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getBorrowGoodsTransfer0rderCode())) {
            queryEsAllocateApplyOrderIndexListRequest.setBorrowGoodsTransfer0rderCode(allocateApplyOrderQueryRequest.getBorrowGoodsTransfer0rderCode());
        }
//        行状态
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getLineStatus())) {
            boolean isStatus = true;
            if (CollectionUtils.isNotEmpty(allocateApplyOrderQueryRequest.getLineStatus())) {
                for (Integer status : allocateApplyOrderQueryRequest.getLineStatus()) {
                    if (99 == status || 10 == status) {
                        isStatus = false;
                    }
                }
            }
            if (isStatus) {
                queryEsAllocateApplyOrderIndexListRequest.setLineStatus(allocateApplyOrderQueryRequest.getLineStatus());
            }
        }

        //筛选sap端处理待回复
//        if (CollectionUtils.isNotEmpty(allocateApplyOrderQueryRequest.getStatus())){
//            for (Integer status:allocateApplyOrderQueryRequest.getStatus()){
//                if (AllocateApplyOrderStatusEnum.WAIT_ANSWER.getCode() == status) {
//                    queryEsAllocateApplyOrderIndexListRequest.setSapEndProcessing(1);
//                }
//            }
//        }
        //TODO 待我回复状态字段没加 先筛选状态
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getAgency())) {
            if (allocateApplyOrderQueryRequest.getAgency()) {
                boolean isStatus = true;
                if (CollectionUtils.isNotEmpty(allocateApplyOrderQueryRequest.getLineStatus())) {
                    for (Integer status : allocateApplyOrderQueryRequest.getLineStatus()) {
                        if (99 == status || 10 == status) {
                            isStatus = false;
                        }
                    }
                }
                if (isStatus) {
                    queryEsAllocateApplyOrderIndexListRequest.setLineStatus(allocateApplyOrderQueryRequest.getLineStatus());
                } else {
                    ArrayList<Integer> status = new ArrayList<>();
                    status.add(AllocateApplyOrderStatusEnum.WAIT_ANSWER.getCode());
                    status.add(AllocateApplyOrderStatusEnum.PART_ANSWER.getCode());
                    if (Objects.isNull(allocateApplyOrderQueryRequest.getOrganizationList()) && Objects.isNull(allocateApplyOrderQueryRequest.getBizUnitList())) {
                        status.add(AllocateApplyOrderStatusEnum.HEADQUARTERS_REPLY.getCode());
                    }
                    status.add(AllocateApplyOrderStatusEnum.SHIPPER_REPLY.getCode());
                    queryEsAllocateApplyOrderIndexListRequest.setLineStatus(status);
                }
                queryEsAllocateApplyOrderIndexListRequest.setSapEndProcessing(0);
            }
        }

//        状态
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getStatus())) {
            boolean isStatus = true;
            if (CollectionUtils.isNotEmpty(allocateApplyOrderQueryRequest.getStatus())) {
                for (Integer status : allocateApplyOrderQueryRequest.getStatus()) {
                    if (99 == status || 10 == status) {
                        isStatus = false;
                    }
                }
            }
            if (isStatus) {
                queryEsAllocateApplyOrderIndexListRequest.setMainStatus(allocateApplyOrderQueryRequest.getStatus());
            }
        }
        //TODO 待我回复状态字段没加 先筛选状态
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getAgency())) {
            if (allocateApplyOrderQueryRequest.getAgency()) {
                if (CollectionUtils.isNotEmpty(allocateApplyOrderQueryRequest.getStatus())) {
                    List<Integer> statusNew = new ArrayList<>();
                    for (Integer status : allocateApplyOrderQueryRequest.getStatus()) {
                        if (AllocateApplyOrderStatusEnum.WAIT_ANSWER.getCode().equals(status)
                                || AllocateApplyOrderStatusEnum.PART_ANSWER.getCode().equals(status)
                                || AllocateApplyOrderStatusEnum.SHIPPER_REPLY.getCode().equals(status)) {
                            statusNew.add(status);
                        }
                        if (Objects.isNull(allocateApplyOrderQueryRequest.getOrganizationList())
                                && Objects.isNull(allocateApplyOrderQueryRequest.getBizUnitList())
                                && AllocateApplyOrderStatusEnum.HEADQUARTERS_REPLY.getCode().equals(status)) {
                            statusNew.add(AllocateApplyOrderStatusEnum.HEADQUARTERS_REPLY.getCode());
                        }
                    }
                    //如果状态过滤完，状态组是空的 给个-1 查不到数据
                    if (CollectionUtils.isNotEmpty(statusNew)) {
                        queryEsAllocateApplyOrderIndexListRequest.setMainStatus(statusNew);
                    } else {
                        statusNew.add(-1);
                        queryEsAllocateApplyOrderIndexListRequest.setMainStatus(statusNew);
                    }
                } else {
                    ArrayList<Integer> status = new ArrayList<>();
                    status.add(AllocateApplyOrderStatusEnum.WAIT_ANSWER.getCode());
                    status.add(AllocateApplyOrderStatusEnum.PART_ANSWER.getCode());
                    if (Objects.isNull(allocateApplyOrderQueryRequest.getOrganizationList()) && Objects.isNull(allocateApplyOrderQueryRequest.getBizUnitList())) {
                        status.add(AllocateApplyOrderStatusEnum.HEADQUARTERS_REPLY.getCode());
                    }
                    status.add(AllocateApplyOrderStatusEnum.SHIPPER_REPLY.getCode());
                    queryEsAllocateApplyOrderIndexListRequest.setMainStatus(status);
                }
                queryEsAllocateApplyOrderIndexListRequest.setSapEndProcessing(0);
            }
        }


//        单据类型
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getType())) {
            queryEsAllocateApplyOrderIndexListRequest.setMainType(allocateApplyOrderQueryRequest.getType());
        }
//        提报组织id
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getApplyOrgId())) {
            IdQueryRequest idQueryRequest = new IdQueryRequest();
            idQueryRequest.setId(allocateApplyOrderQueryRequest.getApplyOrgId());
            idQueryRequest.setType(SALES_ORGANIZATION);
            Result<List<OrganizationSDO>> listResult = organizationQueryService.queryAllChildOrganizationToTargetType(idQueryRequest);
            List<Long> orgIds = new ArrayList<>();
            if (Objects.nonNull(listResult)&&CollectionUtils.isNotEmpty(listResult.getResult())){
                for (OrganizationSDO organizationSDO:listResult.getResult()){
                    if (StringUtils.isNotBlank(organizationSDO.getId())){
                        orgIds.add(Long.valueOf(organizationSDO.getId()));
                    }
                }
            }
            queryEsAllocateApplyOrderIndexListRequest.setApplyOrgId(orgIds);
        }
//        是否直发客户
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getIsDTC())) {
            queryEsAllocateApplyOrderIndexListRequest.setIsDTC(allocateApplyOrderQueryRequest.getIsDTC() ? 1 : 0);
        }
//        客户名称
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getCustomer())) {
            queryEsAllocateApplyOrderIndexListRequest.setCustomerid(allocateApplyOrderQueryRequest.getCustomer());
        }
//        客户地址名称
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getCustomerAddress())) {
            queryEsAllocateApplyOrderIndexListRequest.setCustomerAddress(allocateApplyOrderQueryRequest.getCustomerAddress());
        }
//        收货仓id
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getReceiveWarehouseId())) {
            queryEsAllocateApplyOrderIndexListRequest.setReceiveWarehouseId(allocateApplyOrderQueryRequest.getReceiveWarehouseId().toString());
        }
//        收货库区id
//        if (Objects.nonNull(allocateApplyOrderQueryRequest.getReceiveCargoZoneId())) {
//            queryEsAllocateApplyOrderIndexListRequest.setReceiveWarehouseId(allocateApplyOrderQueryRequest.getReceiveCargoZoneId().toString());
//        }
//        单据时间
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getOrderTimeStart())) {
            queryEsAllocateApplyOrderIndexListRequest.setOrderTimeStart(allocateApplyOrderQueryRequest.getOrderTimeStart().getTime());
        }
//        单据时间
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getOrderTimeEnd())) {
            queryEsAllocateApplyOrderIndexListRequest.setOrderTimeEnd(allocateApplyOrderQueryRequest.getOrderTimeEnd().getTime() + dayTime);
        }
//        提交时间
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getCommitTimeEnd())) {
            queryEsAllocateApplyOrderIndexListRequest.setCommitTimeEnd(allocateApplyOrderQueryRequest.getCommitTimeEnd().getTime() + dayTime);
        }
//        提交时间
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getCommitTimeStart())) {
            queryEsAllocateApplyOrderIndexListRequest.setCommitTimeStart(allocateApplyOrderQueryRequest.getCommitTimeStart().getTime());
        }
//        创建时间
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getGmtCreateStart())) {
            queryEsAllocateApplyOrderIndexListRequest.setGmtCreateStart(allocateApplyOrderQueryRequest.getGmtCreateStart().getTime());
        }
//        创建时间
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getGmtCreateEnd())) {
            queryEsAllocateApplyOrderIndexListRequest.setGmtCreateEnd(allocateApplyOrderQueryRequest.getGmtCreateEnd().getTime() + dayTime);
        }
//        更新时间
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getGmtModifiedStart())) {
            queryEsAllocateApplyOrderIndexListRequest.setGmtModifiedStart(allocateApplyOrderQueryRequest.getGmtCreateStart().getTime());
        }
//        更新时间
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getGmtModifiedEnd())) {
            queryEsAllocateApplyOrderIndexListRequest.setGmtModifiedEnd(allocateApplyOrderQueryRequest.getGmtCreateEnd().getTime() + dayTime);
        }
//        创建人
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getCreator())) {
            queryEsAllocateApplyOrderIndexListRequest.setCreator(allocateApplyOrderQueryRequest.getCreator());
        }
//        销售组织
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getSaleOrganizationCode())) {
            queryEsAllocateApplyOrderIndexListRequest.setSaleOrganizationCode(allocateApplyOrderQueryRequest.getSaleOrganizationCode());
        }
//        销售渠道
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getSaleChannel())) {
            queryEsAllocateApplyOrderIndexListRequest.setSaleChannel(allocateApplyOrderQueryRequest.getSaleChannel());
        }
//        销售部门
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getSaleDepartmentCode())) {
            queryEsAllocateApplyOrderIndexListRequest.setSaleDepartmentCode(allocateApplyOrderQueryRequest.getSaleDepartmentCode());
        }
//        货品名称
//        if (Objects.nonNull(allocateApplyOrderQueryRequest.getTitle())){
//            queryEsAllocateApplyOrderIndexListRequest.setGoodsName(allocateApplyOrderQueryRequest.getTitle());
//        }
//        货品编码
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getTitle())) {
            queryEsAllocateApplyOrderIndexListRequest.setGoodsCode(allocateApplyOrderQueryRequest.getTitle());
        }
//        货品编码
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getScItemId())) {
            queryEsAllocateApplyOrderIndexListRequest.setGoodsCode(allocateApplyOrderQueryRequest.getScItemId());
        }
//        回复时间
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getReplyTimeStart())) {
            queryEsAllocateApplyOrderIndexListRequest.setReplyTimeStart(allocateApplyOrderQueryRequest.getReplyTimeStart().getTime());
        }

//        回复时间
        if (Objects.nonNull(allocateApplyOrderQueryRequest.getReplyTimeEnd())) {
            queryEsAllocateApplyOrderIndexListRequest.setReplyTimeEnd(allocateApplyOrderQueryRequest.getReplyTimeEnd().getTime() + dayTime);
        }
        queryEsAllocateApplyOrderIndexListRequest.setOrganizationList(allocateApplyOrderQueryRequest.getOrganizationList());
        queryEsAllocateApplyOrderIndexListRequest.setBizUnitList(allocateApplyOrderQueryRequest.getBizUnitList());
        queryEsAllocateApplyOrderIndexListRequest.setBizUnitIdReply(allocateApplyOrderQueryRequest.getBizUnitIdReply());
        queryEsAllocateApplyOrderIndexListRequest.setSaleOrgIdReply(allocateApplyOrderQueryRequest.getSaleOrgIdReply());
        //是否小程序提报
        queryEsAllocateApplyOrderIndexListRequest.setIsAppCreate(allocateApplyOrderQueryRequest.getIsAppCreate());
        return queryEsAllocateApplyOrderIndexListRequest;
    }

    //es查询的数据转换
    private AllocateApplyOrderListDTO esAllocateApplyOrderIndexsTransformationAllocateApplyOrderListDTO(EsAllocateApplyOrderIndex esAllocateApplyOrderIndex
            , Map<String, List<AllocateOrderDetailVO>> allocateApplyOrderAndAllocateOrderDetailRelationshipMap,Map<String,CustomerAndAddressInfo> customer,Map<String, JSONObject> warehouseIdMap
            ,Map<String, JSONObject> cargoZoneIdMap,Map<String, String> organizationMap) {
        AllocateApplyOrderListDTO allocateApplyOrderListDTO = new AllocateApplyOrderListDTO();
        //id
        allocateApplyOrderListDTO.setId(esAllocateApplyOrderIndex.getMainId());
        //明细行号
        if (Objects.nonNull(esAllocateApplyOrderIndex.getSubLineNo())) {
            allocateApplyOrderListDTO.setLineNo(esAllocateApplyOrderIndex.getSubLineNo().intValue());
        }
        //外部行号
        if (Objects.nonNull(esAllocateApplyOrderIndex.getSubOutLineNo())) {
            allocateApplyOrderListDTO.setOutLineNo(esAllocateApplyOrderIndex.getSubOutLineNo());
        }
        //预报单编码
        allocateApplyOrderListDTO.setCode(esAllocateApplyOrderIndex.getMainCode());
        //外部预报单号
        allocateApplyOrderListDTO.setOutAllocateApplyOrderId(esAllocateApplyOrderIndex.getMainOutAllocateApplyOrderId());
        //调拨单号 根据预报单号查找，多数量用逗号拼接
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainCode())) {
            List<AllocateOrderDetailVO> allocateOrderDetailVOList = allocateApplyOrderAndAllocateOrderDetailRelationshipMap.get(esAllocateApplyOrderIndex.getMainCode() + esAllocateApplyOrderIndex.getSubGoodsCode());
            if (CollectionUtils.isNotEmpty(allocateOrderDetailVOList)) {
                String allocateOrderNo = "";
                for (AllocateOrderDetailVO allocateOrderDetailVO : allocateOrderDetailVOList) {
                    if (StringUtils.isNotEmpty(allocateOrderNo)) {
                        allocateOrderNo = "," + allocateOrderDetailVO.getCode();
                    } else {
                        allocateOrderNo = allocateOrderDetailVO.getCode();
                    }
                }
                allocateApplyOrderListDTO.setAllocateOrderNo(allocateOrderNo);
            }
        }
        //借货调拨单号
        allocateApplyOrderListDTO.setBorrowGoodsTransfer0rderCode(esAllocateApplyOrderIndex.getMainBorrowGoodsTransfer0rderCode());
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainStatus())) {
            allocateApplyOrderListDTO.setStatus(esAllocateApplyOrderIndex.getMainStatus().intValue());
        }
        //预报单类型
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainType())) {
            allocateApplyOrderListDTO.setType(esAllocateApplyOrderIndex.getMainType().intValue());
        }
        //提报组织 id
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainApplyOrgId())) {
            allocateApplyOrderListDTO.setApplyOrg(esAllocateApplyOrderIndex.getMainApplyOrgId());
        }

        //是否直发客户
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainIsDTC())) {
            allocateApplyOrderListDTO.setIsDTC(1 == esAllocateApplyOrderIndex.getMainIsDTC() ? true : false);
        }
        //客户信息
        if (Objects.nonNull(customer.get(esAllocateApplyOrderIndex.getMainCustomerAddressId()))) {
            CustomerAndAddressInfo customerAndAddressInfo = customer.get(esAllocateApplyOrderIndex.getMainCustomerAddressId());
            //客户编码
            allocateApplyOrderListDTO.setCustomer(customerAndAddressInfo.getCustomerCode());
            //客户名称
            allocateApplyOrderListDTO.setCustomerName(customerAndAddressInfo.getCustomerName());
            //客户地址名称
            allocateApplyOrderListDTO.setCustomerAddressName(customerAndAddressInfo.getAddressName());

            allocateApplyOrderListDTO.setCustomerAddress(customerAndAddressInfo.getAddress());

            //add by myw, add addressCode
            allocateApplyOrderListDTO.setCustomerAddressCode(customerAndAddressInfo.getCustomerAddressCode());
        }
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainGoodsGroup())) {
            allocateApplyOrderListDTO.setGoodsGroup(esAllocateApplyOrderIndex.getMainGoodsGroup().toString());
        }
        //@TODO wwy 和产品确认 先写死 后面改
        allocateApplyOrderListDTO.setGoodsGroupName("常温");
        //收货仓id
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainReceiveCargoZoneId())) {
            //收货仓信息
            JSONObject receiveWarehouse = warehouseIdMap.get(esAllocateApplyOrderIndex.getMainReceiveWarehouseId().toString());
            //收货库区信息
            JSONObject jsonObject = cargoZoneIdMap.get(esAllocateApplyOrderIndex.getMainReceiveCargoZoneId().toString());
            //收货仓id
            allocateApplyOrderListDTO.setReceiveWarehouseId(esAllocateApplyOrderIndex.getMainReceiveWarehouseId().intValue());
            if (Objects.nonNull(receiveWarehouse)) {
                allocateApplyOrderListDTO.setReceiveWarehouseName(receiveWarehouse.getString("name"));
            }
            //收货库区id
            allocateApplyOrderListDTO.setReceiveCargoZoneId(esAllocateApplyOrderIndex.getMainReceiveCargoZoneId().intValue());
            if (Objects.nonNull(jsonObject)) {
                allocateApplyOrderListDTO.setReceiveCargoZoneName(jsonObject.getString("name"));
                //收货仓-地址 @Todo wwy 国庆后面加
                allocateApplyOrderListDTO.setReceiveWarehouseAddress(jsonObject.getString("addressAppend"));
                //收货仓-联系人
                allocateApplyOrderListDTO.setReceiveWarehouseContacts(jsonObject.getString("contactName"));
                //收货仓-电话
                allocateApplyOrderListDTO.setReceiveWarehouseTelephone(jsonObject.getString("contactPhone"));
            }
        }
        //发货仓id
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainShipWarehouseId())) {
            allocateApplyOrderListDTO.setShipWarehouseId(esAllocateApplyOrderIndex.getMainShipWarehouseId().toString());
            JSONObject jsonObject = warehouseIdMap.get(esAllocateApplyOrderIndex.getMainShipWarehouseId().toString());
            if (Objects.nonNull(jsonObject)) {
                //add by myw,for allocate apply order compare 2022-05-27
                JSONObject features = jsonObject.getJSONObject("features");
                if (MapUtils.isNotEmpty(features)) {
                    allocateApplyOrderListDTO.setFactoryCode(features.getString("factoryCode"));
                    allocateApplyOrderListDTO.setInventoryCode(features.getString("warehouseCode"));
                }

            }
        }
        //发货仓
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainShipWarehouseId())) {
            JSONObject jsonObject = warehouseIdMap.get(esAllocateApplyOrderIndex.getMainShipWarehouseId().toString());
            if (Objects.nonNull(jsonObject)) {
                allocateApplyOrderListDTO.setShipWarehouseName(jsonObject.getString("name"));
            }
        }
        //发货仓库
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainShipCargoZoneId())) {
            //收货库区信息
            JSONObject jsonObject = cargoZoneIdMap.get(esAllocateApplyOrderIndex.getMainShipCargoZoneId().toString());
            allocateApplyOrderListDTO.setShipCargoZoneId(esAllocateApplyOrderIndex.getMainShipCargoZoneId().toString());
            if (Objects.nonNull(jsonObject)) {
                allocateApplyOrderListDTO.setShipCargoZoneName(jsonObject.getString("name"));
                //add by myw,for allocate apply order compare 2022-05-27
//                JSONObject features = jsonObject.getJSONObject("features");
//                if (MapUtils.isNotEmpty(features)) {
//                    allocateApplyOrderListDTO.setFactoryCode(features.getString("factoryCode"));
//                    allocateApplyOrderListDTO.setInventoryCode(features.getString("warehouseCode"));
//                }

            }
        }
        //期望交货时间
        allocateApplyOrderListDTO.setHopeDeliveryTime(getStringDate(esAllocateApplyOrderIndex.getMainHopeDeliveryTime()));
        //生效时间
        allocateApplyOrderListDTO.setTakeEffectTime(getStringDate(esAllocateApplyOrderIndex.getMainTakeEffectTime()));
        //失效日期
        allocateApplyOrderListDTO.setInvalidDate(getStringDate(esAllocateApplyOrderIndex.getMainInvalidDate()));
        //单据日期
        allocateApplyOrderListDTO.setOrderTime(getStringDate(esAllocateApplyOrderIndex.getMainOrderTime()));
        //提交时间
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainCommitTime())) {
            allocateApplyOrderListDTO.setCommitTime(new Date(esAllocateApplyOrderIndex.getMainCommitTime()));
        }

        //创建时间
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainGmtCreate())) {
            allocateApplyOrderListDTO.setGmtCreate(new Date(esAllocateApplyOrderIndex.getMainGmtCreate()));
        }
        //更新时间
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainGmtModified())) {
            allocateApplyOrderListDTO.setGmtModified(new Date(esAllocateApplyOrderIndex.getMainGmtModified()));
        }
        //确认时间
        if (Objects.nonNull(esAllocateApplyOrderIndex.getSubReplyDate())) {
            allocateApplyOrderListDTO.setConfirmTime(new Date(esAllocateApplyOrderIndex.getSubReplyDate()));
        }
        //完成时间
        if (Objects.nonNull(esAllocateApplyOrderIndex.getMainCompleteTime())) {
            allocateApplyOrderListDTO.setCompleteTime(new Date(esAllocateApplyOrderIndex.getMainCompleteTime()));
        }
        //创建人
        allocateApplyOrderListDTO.setCreator(InfoUtil.getRealName(esAllocateApplyOrderIndex.getMainCreator()));
        //提交人
//                allocateApplyOrderListDTO.setSubmitter(esAllocateApplyOrderIndex.getMainSubmitter());
        allocateApplyOrderListDTO.setSubmitter(InfoUtil.getRealName(esAllocateApplyOrderIndex.getMainCreator()));
        //修改人
        allocateApplyOrderListDTO.setUpdater(InfoUtil.getRealName(esAllocateApplyOrderIndex.getMainUpdater()));
        //销售组织
        allocateApplyOrderListDTO.setSaleOrganizationCode(esAllocateApplyOrderIndex.getMainSaleOrganizationCode());
        //销售渠道
        allocateApplyOrderListDTO.setSaleChannel(esAllocateApplyOrderIndex.getMainSaleChannel());
        //销售渠道
        allocateApplyOrderListDTO.setSaleDepartmentCode(esAllocateApplyOrderIndex.getMainSaleDepartmentCode());

        //销售部门
        allocateApplyOrderListDTO.setSapInternalSalesBPCode(esAllocateApplyOrderIndex.getMainSapInternalSalesBPCode());
        //总部内部送达方编号
        allocateApplyOrderListDTO.setSapInternalDeliveryBPCode(esAllocateApplyOrderIndex.getMainSapInternalDeliveryBPCode());
        //总部售达方编号
        allocateApplyOrderListDTO.setSapSalesBPCode(esAllocateApplyOrderIndex.getMainSapSalesBPCode());
        //总部送达方编号
        allocateApplyOrderListDTO.setSapDeliveryBPCode(esAllocateApplyOrderIndex.getMainSapDeliveryBPCode());

        //总部成本中心
        allocateApplyOrderListDTO.setSapCostCenter(esAllocateApplyOrderIndex.getMainSapCostCenter());
        //客户采购参考号
        allocateApplyOrderListDTO.setSapRefPoNo(esAllocateApplyOrderIndex.getMainSapRefPoNo());
        //总部渠道编码
        allocateApplyOrderListDTO.setHeadquartersChannelCode(esAllocateApplyOrderIndex.getMainHeadquartersChannelCode());
        //总部组织编码
        allocateApplyOrderListDTO.setHeadquartersOrganizationCode(esAllocateApplyOrderIndex.getMainHeadquartersOrganizationCode());
        //remark
        allocateApplyOrderListDTO.setRemark(esAllocateApplyOrderIndex.getMainRemark());
        //货品id
        allocateApplyOrderListDTO.setGoodsId(esAllocateApplyOrderIndex.getSubGoodsId());
        //货品名称
        allocateApplyOrderListDTO.setTitle(esAllocateApplyOrderIndex.getSubGoodsName());
        //货品编码
        allocateApplyOrderListDTO.setScItemId(esAllocateApplyOrderIndex.getSubGoodsCode());
        //提报数量
        allocateApplyOrderListDTO.setApplyQuantity(Objects.nonNull(esAllocateApplyOrderIndex.getSubApplyQuantity()) ? esAllocateApplyOrderIndex.getSubApplyQuantity().intValue() : 0);
        //回复数量
        allocateApplyOrderListDTO.setReplyQuantity(Objects.nonNull(esAllocateApplyOrderIndex.getSubReplyQuantity()) ? esAllocateApplyOrderIndex.getSubReplyQuantity().intValue() : 0);
        //未回复数量
        allocateApplyOrderListDTO.setNoReplyQuantity(allocateApplyOrderListDTO.getApplyQuantity() - allocateApplyOrderListDTO.getReplyQuantity());
        List<AllocateOrderDetailVO> allocateOrderDetailVOs = allocateApplyOrderAndAllocateOrderDetailRelationshipMap.get(esAllocateApplyOrderIndex.getMainCode() + esAllocateApplyOrderIndex.getSubGoodsCode());
        //确认量
        Integer confirmQuantity = null;
        //发货数量
        Integer shipQuantity = null;
        //未发量 确认量-发货量
        Integer notIssuedQuantity = null;
        //到货量
        Integer receiveQuantity = null;
        Set<String> logisticsInformations = new HashSet<>();
        String logisticsInformation = null;
        if (CollectionUtils.isNotEmpty(allocateOrderDetailVOs)) {
            for (AllocateOrderDetailVO allocateOrderDetailVO : allocateOrderDetailVOs) {
                //未发量
                if (Objects.nonNull(allocateOrderDetailVO.getConfirmQuantity())&&!allocateOrderDetailVO.getClosed()) {

                    // fix by myw 关闭的调拨单不需要累加确认数量
                    if (Objects.isNull(confirmQuantity)) {
                        confirmQuantity = stringTransformationInteger(allocateOrderDetailVO.getConfirmQuantity());
                    } else {
                        confirmQuantity = confirmQuantity + stringTransformationInteger(allocateOrderDetailVO.getConfirmQuantity());
                    }
                }
                //发货数量
                if (Objects.nonNull(allocateOrderDetailVO.getShipQuantity())) {
                    if (Objects.isNull(shipQuantity)) {
                        shipQuantity = stringTransformationInteger(allocateOrderDetailVO.getShipQuantity());
                    } else {
                        shipQuantity = shipQuantity + stringTransformationInteger(allocateOrderDetailVO.getShipQuantity());
                    }
                }
                //到货量
                if (Objects.nonNull(allocateOrderDetailVO.getReceiveQuantity())) {
                    if (Objects.isNull(receiveQuantity)) {
                        receiveQuantity = stringTransformationInteger(allocateOrderDetailVO.getReceiveQuantity());
                    } else {
                        receiveQuantity = receiveQuantity + stringTransformationInteger(allocateOrderDetailVO.getReceiveQuantity());
                    }
                }
                //物流信息使用set去重操作
                if (StringUtils.isNotBlank(allocateOrderDetailVO.getLogisticsInfo())) {
                    String[] split = allocateOrderDetailVO.getLogisticsInfo().split(",");
                    for (int i = 0; i < split.length; i++) {
                        logisticsInformations.add(split[i]);
                    }
                }
            }
        }
        //确认量
        allocateApplyOrderListDTO.setConfirmQuantity(confirmQuantity);
        //发货数量
        allocateApplyOrderListDTO.setDeliverQuantity(shipQuantity);
//        未发量 提报量-发货量
        // 未发量，确认量-发货量
        if (Objects.nonNull(allocateApplyOrderListDTO.getConfirmQuantity())) {
            allocateApplyOrderListDTO.setNotIssuedQuantity(allocateApplyOrderListDTO.getConfirmQuantity() - (Objects.nonNull(shipQuantity) ? shipQuantity : 0));
//            allocateApplyOrderListDTO.setNotIssuedQuantity(allocateApplyOrderListDTO.getApplyQuantity() - (Objects.nonNull(shipQuantity) ? shipQuantity : 0));
        }
        //到货量
        allocateApplyOrderListDTO.setArrivalQuantity(receiveQuantity);
        //单位
        allocateApplyOrderListDTO.setUom(esAllocateApplyOrderIndex.getSubUom());
        allocateApplyOrderListDTO.setUom(InfoUtil.convertUnit(esAllocateApplyOrderIndex.getSubUom()));
        //回复时间
        if (Objects.nonNull(esAllocateApplyOrderIndex.getSubReplyDate())) {
            allocateApplyOrderListDTO.setReplyDate(new Date(esAllocateApplyOrderIndex.getSubReplyDate()));
        }
        //是否关闭
        if (Objects.nonNull(esAllocateApplyOrderIndex.getSubIsClosed())) {
            allocateApplyOrderListDTO.setIsClosed(esAllocateApplyOrderIndex.getSubIsClosed() == 1 ? true : false);
        }
        allocateApplyOrderListDTO.setIsClosedName(Objects.nonNull(allocateApplyOrderListDTO.getIsClosed()) ? (allocateApplyOrderListDTO.getIsClosed() ? "是" : "否") : "否");
        //拒绝原因
        allocateApplyOrderListDTO.setCloseReason(esAllocateApplyOrderIndex.getSubCloseReason());
        //拒绝原因描述
        if (Objects.nonNull(allocateApplyOrderListDTO.getCloseReason())) {
            ReasonForRejectionEnum reasonForRejectionByCode = EnumUtils.getReasonForRejectionByCode(allocateApplyOrderListDTO.getCloseReason());
            if (Objects.nonNull(reasonForRejectionByCode)) {
                allocateApplyOrderListDTO.setCloseReasonDescribe(reasonForRejectionByCode.getDesc());
            } else {
                allocateApplyOrderListDTO.setCloseReasonDescribe("");
            }
        }
        //行备注
        allocateApplyOrderListDTO.setItemRemark(esAllocateApplyOrderIndex.getSubRemark());
        //是否需要还货
        allocateApplyOrderListDTO.setSendBackRequired(esAllocateApplyOrderIndex.getSubSendBackRequired());
        if (Objects.nonNull(esAllocateApplyOrderIndex.getSubSendBackRequired())) {
            allocateApplyOrderListDTO.setSendBackRequiredName("0".equals(esAllocateApplyOrderIndex.getSubSendBackRequired()) ? "否" : "是");
        } else {
            allocateApplyOrderListDTO.setSendBackRequiredName("否");
        }
        //运输方式
        allocateApplyOrderListDTO.setShipMethod(esAllocateApplyOrderIndex.getMainShipMethod());
        //物流信息
        for (String logisticsInformationString : logisticsInformations) {
            if (StringUtils.isEmpty(logisticsInformation)) {
                logisticsInformation = logisticsInformationString;
            } else {
                logisticsInformation = logisticsInformation + "," + logisticsInformationString;
            }
        }
        //物流信息
        allocateApplyOrderListDTO.setLogisticsInformation(logisticsInformation);
        //发货仓类型
        allocateApplyOrderListDTO.setShipWarehouseType(esAllocateApplyOrderIndex.getMainShipWarehouseType());
        //单价
        if (Objects.nonNull(esAllocateApplyOrderIndex.getSubUnitPrice())) {
            allocateApplyOrderListDTO.setUnitPrice(esAllocateApplyOrderIndex.getSubUnitPrice());
        }
        //小计金额
        if (Objects.nonNull(esAllocateApplyOrderIndex.getSubSubtotalMoney())) {
            allocateApplyOrderListDTO.setSubtotalMoney(esAllocateApplyOrderIndex.getSubSubtotalMoney());
        }
        //折扣 (单价×数量-小计金额（折后金额，小计金额等于空，就取单价×数量）)
        if (Objects.nonNull(allocateApplyOrderListDTO.getUnitPrice()) && Objects.nonNull(allocateApplyOrderListDTO.getApplyQuantity())) {
//                    单价*提报数量 – 小计金额
            BigDecimal discount = allocateApplyOrderListDTO.getUnitPrice().multiply(new BigDecimal(allocateApplyOrderListDTO.getApplyQuantity()));
            //小计金额 = 折后金额
            if (Objects.isNull(allocateApplyOrderListDTO.getSubtotalMoney())) {
                allocateApplyOrderListDTO.setSubtotalMoney(discount);
            }
            if (Objects.nonNull(allocateApplyOrderListDTO.getSubtotalMoney())) {
                allocateApplyOrderListDTO.setDiscount(discount.subtract(allocateApplyOrderListDTO.getSubtotalMoney()));
            } else {
                allocateApplyOrderListDTO.setDiscount(discount);
            }
        }
        //结算金额
        allocateApplyOrderListDTO.setExchangeAmt(esAllocateApplyOrderIndex.getSubExchangeAmt());
        //行状态
        if (Objects.nonNull(esAllocateApplyOrderIndex.getSubStatus())) {
            allocateApplyOrderListDTO.setLineStatus(esAllocateApplyOrderIndex.getSubStatus().toString());
        }
        //行状态名称
        if (Objects.nonNull(esAllocateApplyOrderIndex.getSubStatus())) {
            allocateApplyOrderListDTO.setLineStatusName(EnumUtils.getAllocateApplyOrderStatusEnum(esAllocateApplyOrderIndex.getSubStatus().intValue()));
        } else {
            allocateApplyOrderListDTO.setLineStatusName(EnumUtils.getAllocateApplyOrderStatusEnum(esAllocateApplyOrderIndex.getMainStatus().intValue()));
        }
        //单据原因
        allocateApplyOrderListDTO.setDocumentReason(esAllocateApplyOrderIndex.getMainDocumentReason());
        //单据原因名称
        if (Objects.nonNull(allocateApplyOrderListDTO.getDocumentReason())) {
            allocateApplyOrderListDTO.setDocumentReasonName(EnumUtils.getDocumentReasonByCode(allocateApplyOrderListDTO.getDocumentReason()).getDesc());
        }
        //运输方式
        if (Objects.nonNull(allocateApplyOrderListDTO.getShipMethod())) {
            TransportModeEnum transportModeEnum = EnumUtils.getTransportModeByCode(allocateApplyOrderListDTO.getShipMethod());
            if (transportModeEnum != null) {
                allocateApplyOrderListDTO.setShipMethodName(Objects.nonNull(transportModeEnum) ? transportModeEnum.getDesc() : "");
            } else {
                if (allocateApplyOrderListDTO.getShipMethod() == null) {
                    allocateApplyOrderListDTO.setShipMethodName("");
                } else {
                    String shipMethodDesc = InfoUtil.getShipMethodDesc(Integer.parseInt(allocateApplyOrderListDTO.getShipMethod()));
                    if (StringUtils.isNotBlank(shipMethodDesc)) {
                        allocateApplyOrderListDTO.setShipMethodName(shipMethodDesc);
                    }
                }
            }

        }
        //是否直发客户
        if (Objects.nonNull(allocateApplyOrderListDTO.getIsDTC())) {
            allocateApplyOrderListDTO.setIsDTCName(allocateApplyOrderListDTO.getIsDTC() ? "是" : "否");
        } else {
            allocateApplyOrderListDTO.setIsDTCName("否");
        }
        //调拨类型
        if (Objects.nonNull(allocateApplyOrderListDTO.getType())) {
            allocateApplyOrderListDTO.setTypeName(
                    EnumUtils.getAllocateOrderTypeByCode(Integer.valueOf(allocateApplyOrderListDTO.getType())).getDesc());
        }
        //状态名称
        if (Objects.nonNull(allocateApplyOrderListDTO.getStatus())) {
            allocateApplyOrderListDTO.setStatusName(EnumUtils.getAllocateApplyOrderStatusEnum(allocateApplyOrderListDTO.getStatus()));
        }
        //提报组织名称
        if (Objects.nonNull(allocateApplyOrderListDTO.getApplyOrg())) {
            allocateApplyOrderListDTO.setApplyOrgName(organizationMap.get(allocateApplyOrderListDTO.getApplyOrg().toString()));
        }
        //销售组织名称 需要接口查找
        if (Objects.nonNull(allocateApplyOrderListDTO.getSaleOrganizationCode())) {
            allocateApplyOrderListDTO.setSaleOrganizationName(organizationMap.get(allocateApplyOrderListDTO.getSaleOrganizationCode()));
        }
        //分公司客户编码
        allocateApplyOrderListDTO.setBranchCustomersCode(esAllocateApplyOrderIndex.getMainBranchCustomersCode());
        //是否小程序提报
        allocateApplyOrderListDTO.setIsAppCreate(InfoUtil.getBoolean(esAllocateApplyOrderIndex.getMainIsAppCreate()));
        //是否小程序提报 描述
        allocateApplyOrderListDTO.setIsAppCreateDesc(InfoUtil.getBooleanDesc(esAllocateApplyOrderIndex.getMainIsAppCreate()));
        return allocateApplyOrderListDTO;
    }

    private Integer stringTransformationInteger(String s) {
        if (StringUtils.isEmpty(s)) {
            return 0;
        }
        return Double.valueOf(InfoUtil.trim(s)).intValue();
    }

    private static String getStringDate(Long date) {
        String s = "";
        if (Objects.nonNull(date)) {
            s = OtsDateUtils.formatDate(new Date(date), OtsDateUtils.DATE_FORMAT);
        }
        return s;
    }

    /**
     * 填充调拨预报单的分公司客户信息
     * @param esAllocateApplyOrderIndices
     * @param allocateApplyOrderListDTOS
     */
    private void enrichBranchCustomerInfo(List<EsAllocateApplyOrderIndex> esAllocateApplyOrderIndices, List<AllocateApplyOrderListDTO> allocateApplyOrderListDTOS) {
        if (CollectionUtils.isEmpty(esAllocateApplyOrderIndices)) {
            return;
        }
        List<String> codes = esAllocateApplyOrderIndices.stream().filter(x -> StringUtils.isNotBlank(x.getMainBranchCustomersCode()))
                .map(EsAllocateApplyOrderIndex::getMainBranchCustomersCode).distinct().collect(Collectors.toList());
        if (CollectionUtils.isEmpty(codes)) {
            return;
        }
        BatchQueryCustomersRequest queryCustomersRequest = new BatchQueryCustomersRequest();
        queryCustomersRequest.setCodes(codes);
        Object customerResult = otsPlatformEnhanceService.batchQueryCustomers(queryCustomersRequest);
        if (customerResult == null) {
            logger.error("batchQueryCustomersError, result null, request:{}", queryCustomersRequest);
        }
        JSONObject jsonObject = JSON.parseObject(JSON.toJSONString(customerResult));
        if (BooleanUtils.isNotTrue(jsonObject.getBoolean("success"))) {
            logger.error("batchQueryCustomersError, success false, request:{}", queryCustomersRequest);
        }
        JSONArray jsonArray = jsonObject.getJSONArray("result");
        Map<String, String> customerMap = Maps.newHashMap();
        if (!jsonArray.isEmpty()) {
            for (int i = 0; i < jsonArray.size(); i++) {
                JSONObject temp = jsonArray.getJSONObject(0);
                if (temp != null) {
                    customerMap.put(temp.getString("code"), temp.getString("name"));
                }
            }
        }
        for (AllocateApplyOrderListDTO orderListDTO : allocateApplyOrderListDTOS) {
            String branchCustomerCode = orderListDTO.getBranchCustomersCode();
            orderListDTO.setBranchCustomersName(customerMap.get(branchCustomerCode));
        }
    }
}
